package cn.ibizlab.businesscentral.centralapi.rest;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.ServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PostAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import cn.ibizlab.businesscentral.centralapi.dto.*;
import cn.ibizlab.businesscentral.centralapi.mapping.*;
import cn.ibizlab.businesscentral.core.base.domain.Organization;
import cn.ibizlab.businesscentral.core.base.service.IOrganizationService;
import cn.ibizlab.businesscentral.core.base.filter.OrganizationSearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"组织" })
@RestController("CentralApi-organization")
@RequestMapping("")
public class OrganizationResource {

    @Autowired
    public IOrganizationService organizationService;

    @Autowired
    @Lazy
    public OrganizationMapping organizationMapping;

    @PreAuthorize("hasPermission(this.organizationMapping.toDomain(#organizationdto),'iBizBusinessCentral-Organization-Create')")
    @ApiOperation(value = "新建组织", tags = {"组织" },  notes = "新建组织")
	@RequestMapping(method = RequestMethod.POST, value = "/organizations")
    public ResponseEntity<OrganizationDTO> create(@RequestBody OrganizationDTO organizationdto) {
        Organization domain = organizationMapping.toDomain(organizationdto);
		organizationService.create(domain);
        OrganizationDTO dto = organizationMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.organizationMapping.toDomain(#organizationdtos),'iBizBusinessCentral-Organization-Create')")
    @ApiOperation(value = "批量新建组织", tags = {"组织" },  notes = "批量新建组织")
	@RequestMapping(method = RequestMethod.POST, value = "/organizations/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<OrganizationDTO> organizationdtos) {
        organizationService.createBatch(organizationMapping.toDomain(organizationdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "organization" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.organizationService.get(#organization_id),'iBizBusinessCentral-Organization-Update')")
    @ApiOperation(value = "更新组织", tags = {"组织" },  notes = "更新组织")
	@RequestMapping(method = RequestMethod.PUT, value = "/organizations/{organization_id}")
    public ResponseEntity<OrganizationDTO> update(@PathVariable("organization_id") String organization_id, @RequestBody OrganizationDTO organizationdto) {
		Organization domain  = organizationMapping.toDomain(organizationdto);
        domain .setOrganizationid(organization_id);
		organizationService.update(domain );
		OrganizationDTO dto = organizationMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.organizationService.getOrganizationByEntities(this.organizationMapping.toDomain(#organizationdtos)),'iBizBusinessCentral-Organization-Update')")
    @ApiOperation(value = "批量更新组织", tags = {"组织" },  notes = "批量更新组织")
	@RequestMapping(method = RequestMethod.PUT, value = "/organizations/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<OrganizationDTO> organizationdtos) {
        organizationService.updateBatch(organizationMapping.toDomain(organizationdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.organizationService.get(#organization_id),'iBizBusinessCentral-Organization-Remove')")
    @ApiOperation(value = "删除组织", tags = {"组织" },  notes = "删除组织")
	@RequestMapping(method = RequestMethod.DELETE, value = "/organizations/{organization_id}")
    public ResponseEntity<Boolean> remove(@PathVariable("organization_id") String organization_id) {
         return ResponseEntity.status(HttpStatus.OK).body(organizationService.remove(organization_id));
    }

    @PreAuthorize("hasPermission(this.organizationService.getOrganizationByIds(#ids),'iBizBusinessCentral-Organization-Remove')")
    @ApiOperation(value = "批量删除组织", tags = {"组织" },  notes = "批量删除组织")
	@RequestMapping(method = RequestMethod.DELETE, value = "/organizations/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        organizationService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.organizationMapping.toDomain(returnObject.body),'iBizBusinessCentral-Organization-Get')")
    @ApiOperation(value = "获取组织", tags = {"组织" },  notes = "获取组织")
	@RequestMapping(method = RequestMethod.GET, value = "/organizations/{organization_id}")
    public ResponseEntity<OrganizationDTO> get(@PathVariable("organization_id") String organization_id) {
        Organization domain = organizationService.get(organization_id);
        OrganizationDTO dto = organizationMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取组织草稿", tags = {"组织" },  notes = "获取组织草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/organizations/getdraft")
    public ResponseEntity<OrganizationDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(organizationMapping.toDto(organizationService.getDraft(new Organization())));
    }

    @ApiOperation(value = "检查组织", tags = {"组织" },  notes = "检查组织")
	@RequestMapping(method = RequestMethod.POST, value = "/organizations/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody OrganizationDTO organizationdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(organizationService.checkKey(organizationMapping.toDomain(organizationdto)));
    }

    @PreAuthorize("hasPermission(this.organizationMapping.toDomain(#organizationdto),'iBizBusinessCentral-Organization-Save')")
    @ApiOperation(value = "保存组织", tags = {"组织" },  notes = "保存组织")
	@RequestMapping(method = RequestMethod.POST, value = "/organizations/save")
    public ResponseEntity<Boolean> save(@RequestBody OrganizationDTO organizationdto) {
        return ResponseEntity.status(HttpStatus.OK).body(organizationService.save(organizationMapping.toDomain(organizationdto)));
    }

    @PreAuthorize("hasPermission(this.organizationMapping.toDomain(#organizationdtos),'iBizBusinessCentral-Organization-Save')")
    @ApiOperation(value = "批量保存组织", tags = {"组织" },  notes = "批量保存组织")
	@RequestMapping(method = RequestMethod.POST, value = "/organizations/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<OrganizationDTO> organizationdtos) {
        organizationService.saveBatch(organizationMapping.toDomain(organizationdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Organization-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Organization-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"组织" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/organizations/fetchdefault")
	public ResponseEntity<List<OrganizationDTO>> fetchDefault(OrganizationSearchContext context) {
        Page<Organization> domains = organizationService.searchDefault(context) ;
        List<OrganizationDTO> list = organizationMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Organization-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Organization-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"组织" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/organizations/searchdefault")
	public ResponseEntity<Page<OrganizationDTO>> searchDefault(@RequestBody OrganizationSearchContext context) {
        Page<Organization> domains = organizationService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(organizationMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

